package com.smartpro.mis.modular.business.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.smartpro.mis.core.base.controller.BaseController;
import com.smartpro.mis.core.base.tips.ErrorTip;
import com.smartpro.mis.core.util.MD5Util;
import com.smartpro.mis.modular.business.neo4jEntity.*;
import com.smartpro.mis.modular.business.service.*;
import com.smartpro.mis.modular.system.dao.*;
import com.smartpro.mis.modular.system.model.*;
import com.smartpro.mis.rest.modular.auth.controller.dto.ResponseBean;
import com.smartpro.mis.rest.modular.auth.util.JwtTokenUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.aspectj.bridge.IMessage;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * user控制器
 *
 * @author mengiy
 * @Date 2019-05-07 21:50:18
 */
@RestController
@RequestMapping("/api/service/user")
public class UserController extends BaseController {

    @Autowired
    private IUserService userService;

    @Autowired
    private IMessageService messageService;

    @Autowired
    private IDistributorService distributorService;

    @Autowired
    private IPositionService positionService;

    @Autowired
    private IGroupBuyService groupBuyService;

    @Autowired
    private N4jUserRepository n4jUserRepository;

    @Autowired
    private DistributorExpireRelationRepository distributorExpireRelationRepository;

    @Autowired
    private DistributorProtectRelationRepository distributorProtectRelationRepository;

    @Autowired
    private ClickGroupBuyRelationRepository clickGroupBuyRelationRepository;

    @Autowired
    private ClickLinkRelationRepository clickLinkRelationRepository;

    @Autowired
    private IThirdPartyUserService thirdPartyUserService;
    @Autowired
    JwtTokenUtil jwtTokenUtil;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 用户登录
     */
    @ApiOperation(value ="用户登录",notes = "通过用户名、密码登录")
    @ApiImplicitParam(name = "loginInfo", value = "用户登录信息", required = true, dataType = "JSON")
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public Object login(@RequestBody JSONObject loginInfo ) {
        JSONObject result = new JSONObject();
        JwtTokenUtil jwtTokenUtil = new JwtTokenUtil();
        User userBean;
        String wechat = loginInfo.getString("wechat");
        String password = MD5Util.encrypt(loginInfo.getString("password"));
//        int role = userInfo.getInteger("role");
        Map<String, Object> condition = new HashMap<>();
        condition.put("wechat", wechat);
//        condition.put("password", password);
//        condition.put("role", role);
        List<User> userList = this.userService.selectByMap(condition);
        if (userList.size() > 0) {
            userBean = userList.get(0);
            if(userBean.getPassword().equals(password)){
                JSONObject res = new JSONObject();
                res.put("userInfo",userBean);
                res.put("token",jwtTokenUtil.generateToken(wechat,jwtTokenUtil.getRandomKey()));
                return new ResponseBean(200, "login success", res);
            }else {
                return new ResponseBean(400, "login error", "密码错误" );
            }
        } else {
            return new ResponseBean(400, "login error", "登录信息有误" );
        }

    }

    /**
     * 获取用户列表
     */
    @ApiOperation(value = "获取用户列表",notes = "全部查询")
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    @ResponseBody
    @RequiresAuthentication
    public Object list() {
        return new ResponseBean(200,"query success",userService.selectList(null));
    }

    /**
     * 注册用户
     */
    @RequestMapping(value = "/register",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value ="注册用户")
    @ApiImplicitParam(name = "user", value = "用户详细信息", required = true, dataType = "User")
    public Object register(@RequestBody User user) {

//        String nickName = userInfo.getString("nickName");
//        String headImage = userInfo.getString("headImage");
//        String mobile = userInfo.getString("mobile");
//        String wechat = userInfo.getString("wechat");
//        String password = userInfo.getString("password");
//        String childName = userInfo.getString("childName");
//        int gender = userInfo.getInteger("gender");
//        String childBirthday = userInfo.getString("childBirthday");
//        String province = userInfo.getString("province");
//        String city = userInfo.getString("city");
//        String address = userInfo.getString("address");
//        String tags = userInfo.getString("tags");
//        int role = userInfo.getInteger("role");
//        int purchaseTimes = userInfo.getInteger("purchaseTimes");
//        BigDecimal totalAmount = userInfo.getBigDecimal("totalAmount");
//        int operaterID = userInfo.getInteger("operaterID");
        user.setPassword(MD5Util.encrypt(user.getPassword()));
        user.setCreateTime(sdf.format(new Date()));
        try {
            userService.insert(user);
            Wrapper<User> entityWrapper  = new EntityWrapper<User>();
           ((EntityWrapper<User>) entityWrapper).setEntity(user);
            User user2 =userService.selectList(entityWrapper).get(0);
            this.n4jUserRepository.save(new N4jUser(user.getUserID()));
            return new ResponseBean(200, "register success", JSONObject.toJSON(user));
        }catch (Exception e){
            return new ResponseBean(400, "register error", e.getStackTrace());
        }
    }


    /**
     * 微信注册用户
     */
    @RequestMapping(value = "/wechatRegister",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value ="微信注册用户")
    @ApiImplicitParam(name = "userInfo", value = "微信用户详细信息", required = true, dataType = "JSONObject")
    public Object wechatRegister(@RequestBody JSONObject userInfo) {

        String openid = userInfo.getString("openid");
        String nickName = userInfo.getString("nickName");
        String headImage = userInfo.getString("avatarUrl");
        int gender = Integer.parseInt(userInfo.getString("gender"));
        String country = userInfo.getString("country");
        String province = userInfo.getString("province");
        String city = userInfo.getString("city");
        int distributorID = -1;
        int groupbuyID = -1;
        int productID = -1;
        if(userInfo.containsKey("distributorID")&& null != userInfo.get("distributorID")){
            distributorID = userInfo.getInteger("distributorID");
        }
        if(userInfo.containsKey("groupbuyID") && (null != userInfo.get("groupbuyID"))){
            groupbuyID = userInfo.getInteger("groupbuyID");
        }
        User user = new User();
        user.setNickName(nickName);
        user.setCity(city);
        user.setProvince(province);
        user.setHeadImage(headImage);
        user.setGender(gender);
        user.setPassword(MD5Util.encrypt(user.getNickName()));
        user.setCreateTime(sdf.format(new Date()));

        try {
            userService.insert(user);
            Wrapper<User> entityWrapper  = new EntityWrapper<User>();
            ((EntityWrapper<User>) entityWrapper).setEntity(user);
            User user2 =userService.selectList(entityWrapper).get(0);

            ThirdPartyUser thirdPartyUser = new ThirdPartyUser();
            thirdPartyUser.setGender(gender+"");
            thirdPartyUser.setOpenid(openid);
            thirdPartyUser.setUserId(user.getUserID());
            thirdPartyUser.setAvatarUrl(headImage);
            thirdPartyUser.setUsername(nickName);
            thirdPartyUserService.insert(thirdPartyUser);

            //添加neo4j用户实体
            this.n4jUserRepository.save(new N4jUser(user.getUserID()));


//            如果是团长分享的组团链接，并且团长也不是推广员,那么系统需要知道进入哪个团购活动,需要建立团长和团员之间的点击链接关系
            //有推广员需要建立推广关系
            N4jDistributor virtualN4jDistributor = new N4jDistributor(-1);
            N4jUser n4jUser = new N4jUser(user.getUserID());
            if(distributorID != -1) {
                Distributor distPosition = distributorService.selectById(distributorID);
                Position position = positionService.selectById(distPosition.getPositionID());
                distributorExpireRelationRepository.save(new DistributorExpireRelationship(sdf.format(new Date()), position.getDefaultValidationDays(), new N4jDistributor(distributorID), n4jUser));
                distributorProtectRelationRepository.save(new DistributorProtectRelationship(sdf.format(new Date()), position.getDefaultProtectionDays(), new N4jDistributor(distributorID), n4jUser));
            }else {
                //没有推广员则绑定虚拟推广员
                DistributorProtectRelationship distributorProtectRelationship = new DistributorProtectRelationship(sdf.format(new Date()),0,virtualN4jDistributor,n4jUser);
                DistributorExpireRelationship distributorExpireRelationship = new DistributorExpireRelationship(sdf.format(new Date()),0,virtualN4jDistributor,n4jUser);
                distributorExpireRelationRepository.save(distributorExpireRelationship);
                distributorProtectRelationRepository.save(distributorProtectRelationship);
            }

            if(groupbuyID!=-1){
//                建立点击团购链接
                /**
                 * 1. 建立用户与团长的点击团购商品关系
                 */
                GroupBuy groupBuy = groupBuyService.selectById(groupbuyID);
                int leaderID =  groupBuy.getLeaderID();
                ClickGroupBuyRelationship clickGroupBuyRelationship = new ClickGroupBuyRelationship(sdf.format(new Date()),new N4jUser(leaderID),new N4jUser(user.getUserID()));
                this.clickGroupBuyRelationRepository.save(clickGroupBuyRelationship);
                ClickLinkRelationship clickLinkRelationship = new ClickLinkRelationship(sdf.format(new Date()),new N4jUser(user.getUserID()),new N4jProduct(groupBuy.getProductID()));
                this.clickLinkRelationRepository.save(clickLinkRelationship);
            }

            return new ResponseBean(200, "register success", user);
        }catch (Exception e){
            return new ResponseBean(400, "register error", e.getStackTrace());
        }
    }




    /**
     * 新增用户
     */
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value ="新增用户")
    @ApiImplicitParam(name = "user", value = "用户详细信息", required = true, dataType = "User")
    @RequiresAuthentication
    public Object add(@RequestBody User user) {
        userService.insert(user);
        Wrapper<User> entityWrapper  = new EntityWrapper<User>();
        ((EntityWrapper<User>) entityWrapper).setEntity(user);
        User user2 =userService.selectList(entityWrapper).get(0);
        this.n4jUserRepository.save(new N4jUser(user.getUserID()));
        return new ResponseBean(200, "operation success", JSONObject.toJSON(user));
    }

    /**
     * 删除用户
     */
    @ApiOperation(value ="删除用户")
    @ApiImplicitParam(name = "userID", value = "用户ID", required = true, dataType = "Integer")
    @RequestMapping(value = "/delete/{userID}",method = RequestMethod.GET)
    @ResponseBody
    @RequiresAuthentication
    public Object delete(@PathVariable("userID") Integer userID) {
        userService.deleteById(userID);
        this.n4jUserRepository.delete(new N4jUser(userID));
        return new ResponseBean(200, "operation success", null);
    }

    /**
     * 修改用户
     */
    @ApiOperation(value = "更新用户信息",notes = "根据实体信息进行更新")
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    @ResponseBody
    @RequiresAuthentication
    public Object update(@RequestBody User user) {
        userService.updateById(user);
        return new ResponseBean(200,"update success",userService.selectById(user.getUserID()));
    }


    /**
     * 修改用户密码
     */
    @ApiOperation(value = "修改密码",notes = "使用用户编号、旧密码、新密码修改")
    @ApiImplicitParam(name = "passwdInfo",value = "JSON数据包含元素：userID,oldPassword,newPassword",required = true,dataType = "JSONObject")
    @RequestMapping(value = "/patchChangePassword",method = RequestMethod.POST)
    @ResponseBody
    @RequiresAuthentication
    public Object patchChangePassword(@RequestBody JSONObject passwdInfo) {
        User user = this.userService.selectById(passwdInfo.getInteger("userID"));
        String oldPassword = MD5Util.encrypt(passwdInfo.getString("oldPassword"));
        if(null != user){
        if(user.getPassword().equals(oldPassword)){
            user.setPassword(MD5Util.encrypt(passwdInfo.getString("newPassword")));
            this.userService.updateById(user);
            return new ResponseBean(200, "modify success", JSONObject.toJSON(user));
        }else {
            return new ResponseBean(400, "modify fail", "原密码输入错误.");
        }}else{
            return new ResponseBean(400, "operation fail", "系统无此用户");
        }

    }

    /**
     * 用户详情
     */
    @RequestMapping(value = "/detail/{userId}",method = RequestMethod.GET)
    @ResponseBody
    @RequiresAuthentication
    public Object detail(@PathVariable("userId") Integer userId) {
        return new ResponseBean(200,"operation success",userService.selectById(userId));
    }



    /**
     * 查询用户
     */
    @ApiOperation(value ="查看用户")
    @ApiImplicitParam(name = "userId", value = "用户编号", required = true, dataType = "Integer")
    @RequestMapping(value = "/view/{userId}",method = RequestMethod.GET)
    @ResponseBody
    @RequiresAuthentication
    public Object view(@PathVariable("userId") Integer userId) {
        return new ResponseBean(200,"operation success",userService.selectById(userId));
    }
}
